package com.minelx.serverandclient.connector;

import com.minelx.serverandclient.stream.data.Packet;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

public class PassiveClient {

	private boolean isExit;

	private final ExecutorService service;

	private final Consumer<Packet> consumer;

	private final PacketReader reader;

	public PassiveClient(InputStream in, Consumer<Packet> consumer) {
		this.consumer = consumer;
		reader = new PacketReader(in);
		service = Executors.newSingleThreadExecutor();
	}

	private void receiving() {
		try {
			while (!isExit) {
				consumer.accept(reader.take());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isRunning() {
		return !isExit;
	}

	public void start() {
		isExit = false;
		service.submit(this::receiving);
	}

	public void stop() {
		isExit = true;
	}
}
